package com.topnav.mc.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.js.lib.result.Result;
import com.topnav.mc.admin.bean.OrgDeviceBean;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.DeviceFavorite;
import com.topnav.mc.admin.entity.bean.DeviceFavoriteBean;
import com.topnav.mc.admin.entity.param.DeviceFavoriteParam;
import com.topnav.mc.admin.entity.wrapper.DeviceFavoriteWrapper;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.admin.service.IDeviceFavoriteService;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.base.mc.McController;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.position.PositionInfo;
import com.topnav.mc.position.PositionUtil;
import com.topnav.mc.uitls.DeviceOnlineUtils;
import com.topnav.mc.uitls.MapUtil;
import com.topnav.mc.uitls.PermissionGradeUtil;
import com.topnav.mc.uitls.ResultErrorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: kenny
 * @Date: 2024/1/9 17:03
 */
@RestController
@CrossOrigin
@RequestMapping("admin/device/favorite")
@Slf4j
public class DeviceFavoriteController extends McController<DeviceFavorite, DeviceFavoriteBean, DeviceFavoriteParam, IDeviceFavoriteService, DeviceFavoriteWrapper> {
    @Resource
    private PermissionGradeUtil pmGradeUtil;
    @Autowired
    private IDeviceFavoriteService deviceFavoriteService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private PositionUtil positionUtil;
    @Autowired
    private DeviceOnlineUtils deviceOnlineUtils;

    /**
     * 查询
     * @param param
     * @return
     */
    @PostMapping("/find/by/user")
    @ResponseBody
    public Result findFavoriteByUser(@RequestBody Map<String,String> param){
        List<OrgDeviceBean> beans = new ArrayList<OrgDeviceBean>();
        //当前用户权限
        PermissionGrade permissionGrade = pmGradeUtil.getPmGrade();
        QueryWrapper<DeviceFavoriteParam> queryWrapper = new QueryWrapper();
        queryWrapper.eq("f.user_id",permissionGrade.getUserId());
        String keyword = param.get("keyword");
        if (!StringUtils.isEmpty(keyword)){
            queryWrapper.and(
                    wrapper1->wrapper1.like("d.name",keyword)
                            .or().like("d.code",keyword)
            );
        }

        List<DeviceFavoriteBean> deviceCollectBeans = deviceFavoriteService.listInfo(queryWrapper);

        for(DeviceFavoriteBean collectBean : deviceCollectBeans){
            OrgDeviceBean bean = new OrgDeviceBean();
            bean.setType("chn");
            bean.setTitle(collectBean.getDeviceName());
            bean.setId(collectBean.getDeviceId().toString());
            bean.setCoordinateSystem(collectBean.getCoordinateSystem());
            bean.setDeviceType(2);
            bean.getArrt().put("deviceCode",collectBean.getDeviceCode());
            bean.setOnline(deviceOnlineUtils.isOnline(collectBean.getDeviceCode())?"1":"0");

            PositionInfo positionInfo = null;
            Double longitude = null;
            Double latitude = null;
            String coordinateSystem = null;
            Device device = deviceService.getFromCache(collectBean.getDeviceCode());

            if ((positionInfo = positionUtil.getCurrentPosition(collectBean.getDeviceCode())) != null){
                longitude = positionInfo.getLongitude();
                latitude = positionInfo.getLatitude();
                coordinateSystem = positionInfo.getCoordinateSystem();
            }else{
                //取此设备最后的定位
                longitude = device.getLongitude();
                latitude = device.getLatitude();
                coordinateSystem = device.getCoordinateSystem();
            }
                //设备状态信息
            bean.getArrt().put("batteryInfo",device.getBatteryInfo());
            bean.getArrt().put("storage",device.getStorage());
            bean.getArrt().put("usedMemory",device.getUsedMemory());
            bean.getArrt().put("remainMemory",device.getRemainMemory());
            bean.getArrt().put("recordStatus",device.getRecordStatus());

            if (longitude == null || 0.0==longitude){
                //取中心点
                Map<String,Double> point = MapUtil.getCenterPoint();
                longitude = point.get("longitude").doubleValue();
                latitude = point.get("latitude").doubleValue();
            }
            if (bean.getChildren()!=null && bean.getChildren().size()>0){
                for(OrgDeviceBean child: bean.getChildren()){
                    child.setLongitude(longitude);
                    child.setLongitude(latitude);
                    child.setCoordinateSystem(coordinateSystem);
                }
            }
            bean.setLongitude(longitude);
            bean.setLatitude(latitude);
            bean.setCoordinateSystem(coordinateSystem);
            beans.add(bean);
        }

        return Result.ok(beans);
    }

    /**
     * 收藏
     * @param param
     * @return
     */
    @PostMapping("/new")
    @ResponseBody
    public Result addFavorite(@RequestBody DeviceFavoriteParam param){
        if (param == null || StringUtils.isEmpty(param.getDeviceCode())) {
            log.error("参数不全");
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_PARAM_INCOMPLETE);
        }

        PermissionGrade permissionGrade = pmGradeUtil.getPmGrade();
        Device device = deviceService.getFromCache(param.getDeviceCode());
        if (device == null){
            log.error(String.format("不存在的设备[%s]",param.getDeviceCode()));
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_NOT_EXISTS_EXCEPTION);
        }

        QueryWrapper<DeviceFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",permissionGrade.getUserId());
        queryWrapper.eq("device_id",device.getId());
        if (deviceFavoriteService.getOne(queryWrapper,false) == null){
            DeviceFavorite deviceFavorite = new DeviceFavorite();
            deviceFavorite.setDeviceId(device.getId() );
            deviceFavorite.setUserId(permissionGrade.getUserId());
            deviceFavoriteService.save(deviceFavorite);
        }
        return Result.ok("收藏成功");
    }

    /**
     * 取消收藏
     * @param param
     * @return
     */
    @PostMapping("/cancel")
    @ResponseBody
    public Result cancelFavorite(@RequestBody DeviceFavoriteParam param){
        if (param == null || StringUtils.isEmpty(param.getDeviceCode())) {
            log.error("参数不全");
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_PARAM_INCOMPLETE);
        }

        PermissionGrade permissionGrade = pmGradeUtil.getPmGrade();
        Device device = deviceService.getFromCache(param.getDeviceCode());
        if (device == null){
            log.error(String.format("不存在的设备[%s]",param.getDeviceCode()));
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_NOT_EXISTS_EXCEPTION);
        }

        QueryWrapper<DeviceFavorite> wrapper = new QueryWrapper();
        wrapper.eq("user_id",permissionGrade.getUserId());
        wrapper.eq("device_id",device.getId());
        deviceFavoriteService.remove(wrapper);
        return Result.ok("取消收藏成功");
    }
}
